import { ref, onUnmounted } from "vue";
import { getToken } from "@/utils";

export function useChat(outputFlag = "●") {
  const response = ref(""); // AI 回复的消息
  const isPaused = ref(true); // 对话是否暂停
  const salutatory = ref("欢迎！我是小龙腾，很高兴为您生成文案！\n\n"); // 欢迎语
  const timeouts = [];
  const chatUrl = "http://localhost:3100/api/chatbot/stream-chat";

  const clearAllTimeouts = () => {
    timeouts.forEach(clearTimeout);
    timeouts.length = 0;
  };

  const chat = async (messages) => {
    isPaused.value = false;
    response.value = outputFlag;
    try {
      const resp = await fetch(chatUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: getToken(),
        },
        body: JSON.stringify(messages),
      });
      for (let i = 0; i < salutatory.value.length; i++) {
        if (isPaused.value) {
          isPaused.value = false;
          return;
        }
        await addChar(salutatory.value[i]);
      }
      const reader = resp.body.getReader();
      const decoder = new TextDecoder();
      let isReading = true;
      while (isReading) {
        const { done, value } = await reader.read();
        if (done) {
          isReading = false;
        }
        const datas = decoder.decode(value).trim().split("\n");
        for (let data of datas) {
          data = data.replace(/data:/g, "").trim();
          if (data === "") {
            continue;
          }
          const result = JSON.parse(data).result;
          console.log("result: ", result);
          for (let i = 0; i < result.length; i++) {
            if (isPaused.value) {
              isPaused.value = false;
              return;
            }
            await addChar(result[i]);
          }
        }
      }
    } catch (e) {
      console.error(e);
    } finally {
      isPaused.value = true;
      response.value = response.value.slice(0, -1);
      clearAllTimeouts();
    }
  };

  const addChar = (character) => {
    return new Promise((resolve) => {
      const timeoutId = setTimeout(() => {
        response.value = response.value.slice(0, -1);
        response.value += character + outputFlag;
        resolve();
      }, 30);
      timeouts.push(timeoutId);
    });
  };

  onUnmounted(() => {
    clearAllTimeouts();
  });

  return { response, isPaused, chat };
}
